# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor

label = f"dwd_trunk_error_scan_detail{int(time())}"
timeout = timedelta(minutes=10).seconds
doris_dwd_trunk_error_scan_detail_dt = RichSqlSensor(
    task_id='doris_dwd_trunk_error_scan_detail_dt',
    pool='broker_load_pool',
    email=['yushuo@jtexpress.com'],
    task_concurrency=1,
    conn_id='new_doris',
    pre_sql=f"""
                 TRUNCATE TABLE jms_dwd.dwd_trunk_error_scan_detail PARTITION (p{{{{ execution_date | cst_ds_nodash }}}},p{{{{ execution_date | date_add(-1) | cst_ds_nodash }}}}, p{{{{ execution_date | date_add(-2) | cst_ds_nodash }}}});
                 LOAD LABEL jms_dwd.{label} (
                     DATA INFILE(
                                 "hdfs://yl-bg-hdp/dw/hive/jms_dm.db/external/dm_trunk_error_scan_detail/dt={{{{ execution_date | date_add(-2) | cst_ds }}}}/*",
                                 "hdfs://yl-bg-hdp/dw/hive/jms_dm.db/external/dm_trunk_error_scan_detail/dt={{{{ execution_date | date_add(-1) | cst_ds }}}}/*",
                                 "hdfs://yl-bg-hdp/dw/hive/jms_dm.db/external/dm_trunk_error_scan_detail/dt={{{{ execution_date | cst_ds }}}}/*")
                     INTO TABLE dwd_trunk_error_scan_detail
                     FORMAT AS 'PARQUET'
                     (waybill_no,shipment_no,scan_site_code,scan_site ,next_station_code ,next_station,scan_type ,scan_user ,scan_time ,shipment_sites_codes)
                     columns from path as (dt)
                     set(waybill_no=waybill_no,shipment_no=shipment_no,scan_site_code=scan_site_code,scan_site=scan_site,next_station_code=next_station_code,next_station=next_station,scan_type=scan_type,scan_user=scan_user,scan_time=scan_time,dt=dt)
                 )
                 WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
                 PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dwd WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dwd WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

